package serializable;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class Test1 {

	public static void main(String[] args) {
		User1 user = new User1();
		user.setName("hollis1");
		user.setAge(21);
		System.out.println(user);

		// 序列化到本地磁盘文件
		try {
			FileOutputStream fos = new FileOutputStream("tempfile1");
			ObjectOutputStream oos = new ObjectOutputStream(fos);
			oos.writeObject(user);
		} catch (Exception e) {
			e.printStackTrace();
		}

		// 从本地磁盘文件中反序列化
		try {
			File file = new File("tempfile1");
			FileInputStream fis = new FileInputStream(file);
			ObjectInputStream ois = new ObjectInputStream(fis);
			User1 user2 = (User1) ois.readObject();
			System.out.println(user2);
		} catch (Exception e) {
			e.printStackTrace();
		}

		// try - with - resource
		try (FileInputStream fis = new FileInputStream(new File("tempfile1"));
				ObjectInputStream ois = new ObjectInputStream(fis);) {
			User1 user3 = (User1) ois.readObject();
			System.out.println(user3);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}
